package com.zixi.ai.framework.entity.page;

import com.zixi.ai.common.utils.ServletUtils;
import com.zixi.ai.common.utils.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

/**
 * 表格数据处理
 *
 * @author wfg
 */
public class QueryPageSupport {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "page";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "size";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String ORDER_BY = "orderBy";

    /**
     * 封装分页对象
     */
    public static PageRequest getPageDomain() {
        Sort sort = null;
        if (StringUtils.isNotBlank(ServletUtils.getParameter(ORDER_BY_COLUMN)) && !"undefined".equalsIgnoreCase(ServletUtils.getParameter(ORDER_BY_COLUMN))) {
            if ("asc".equalsIgnoreCase(ServletUtils.getParameter(ORDER_BY))) {
                sort = Sort.by(Sort.Direction.ASC, ServletUtils.getParameter(ORDER_BY_COLUMN));
            } else {
                sort = Sort.by(Sort.Direction.DESC, ServletUtils.getParameter(ORDER_BY_COLUMN));
            }
        }
        return PageRequest.of(ServletUtils.getParameterToInt(PAGE_NUM, 1) - 1,
                ServletUtils.getParameterToInt(PAGE_SIZE, 10), sort != null ? sort : Sort.unsorted());
    }
    public static int getPageNo() {
        return ServletUtils.getParameterToInt(PAGE_NUM, 1) -1;
    }
    public static int getPageSize() {
        return ServletUtils.getParameterToInt(PAGE_SIZE, 10);
    }
    public static String getOrderByColumn() {
        return ServletUtils.getParameter(ORDER_BY_COLUMN);
    }
    public static PageRequest buildPageRequest() {
        return getPageDomain();
    }
}
